/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.speed;

import java.util.ArrayList;
import java.util.Collection;
import org.apache.log4j.Logger;

/**
 *
 * @author zwlin
 */
public class SpeedLimiterAdaptor implements SpeedLimiter {

	private static final Logger logger = Logger.getLogger(SpeedLimiterAdaptor.class);

	private ArrayList<SpeedLimiter> limiters;
	private boolean activated;

	public SpeedLimiterAdaptor() {
		this.limiters = new ArrayList<>();
	}

	public SpeedLimiterAdaptor(ArrayList<SpeedLimiter> limiters) {
		this.limiters = limiters;
	}

	public void regSpeedLimiter(SpeedLimiter limiter) {
		limiters.add(limiter);
	}

	public void regSpeedLimiter(Collection<SpeedLimiter> limiters) {
		limiters.addAll(limiters);
	}

	@Override
	public boolean tryGetThrough(String key) {
		if (!activated) {
			logger.warn("SpeedLimiterAdaptor stopped.");
			return false;
		} else {
			boolean through = true;
			for (SpeedLimiter limiter : limiters) {
				if (!limiter.tryGetThrough(key)) {
					through = false;
				}
			}
			return through;
		}
	}

	@Override
	public void waitGetThrough(String key) {
		if (!activated) {
			logger.warn("SpeedLimiterAdaptor stopped.");
			return;
		} else {
			for (SpeedLimiter limiter : limiters) {
				limiter.waitGetThrough(key);
			}
		}
	}

	@Override
	public void start() {
		if (!activated) {
			synchronized (this) {
				if (!activated) {
					for (SpeedLimiter limiter : limiters) {
						limiter.start();
					}
					activated = true;
				}
			}
		}
	}

	@Override
	public void stop() {
		if (activated) {
			synchronized (this) {
				if (activated) {
					activated = false;
					for (SpeedLimiter limiter : limiters) {
						limiter.stop();
					}

				}
			}
		}
	}

	@Override
	public boolean isActivated() {
		return activated;
	}

}
